package com.item.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.easysdk.factory.Factory;
import com.item.configration.AlipayConfig;
import com.item.pojo.AliPay;
import com.item.service.RechargeRecordService;
import com.item.service.foodservice;
import com.item.service.userservice;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;


/**
 * @author XXDLD
 */
@RestController
@AllArgsConstructor
@RequestMapping("/alipay")
@Transactional(rollbackFor = Exception.class)
public class AliPayController {

    @Resource
    AlipayConfig aliPayConfig;
    private RedisTemplate redisTemplate;
private foodservice foodservice;
    private com.item.service.userservice userservice;
    private RechargeRecordService rechargeRecordService;

    // 支付宝网关URL、格式、字符集、签名类型等配置
    private static final String GATEWAY_URL ="https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT ="JSON";
    private static final String CHARSET ="utf-8";
    private static final String SIGN_TYPE ="RSA2";

    /**
     * 处理前端发起的支付请求，生成支付表单并返回给前端。
     *
     * @param aliPay 包含支付信息的对象，如订单号、金额、主题等
     * @param httpResponse 用于直接向客户端响应的HttpServletResponse对象
     * @throws Exception 可能抛出的异常，包括支付宝接口调用异常等
     */
    @GetMapping("/pay") // 前端路径参数格式?subject=xxx&traceNo=xxx&totalAmount=xxx
    public void pay(AliPay aliPay, HttpServletResponse httpResponse) throws Exception {

        // 创建支付宝客户端
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);

        // 配置支付请求参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        request.setReturnUrl(aliPayConfig.getReturnUrl());
        request.setBizContent("{\"out_trade_no\":\"" + aliPay.getTraceNo() + "\","
                + "\"total_amount\":\"" + aliPay.getTotalAmount() + "\","
                + "\"subject\":\"" + aliPay.getSubject() + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        // 调用支付宝接口，生成支付表单
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        // 将表单直接输出到前端页面
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    /**
     * 处理支付宝异步通知请求，验证通知数据并处理支付结果。
     *
     * @param request 包含支付宝回调参数的HttpServletRequest对象
     * @return 返回给支付宝的处理结果字符串
     * @throws Exception 可能抛出的异常，包括数据验证和业务处理异常
     */
    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        // 检查交易状态
        String tradeStatus = request.getParameter("trade_status");
        if (tradeStatus != null && tradeStatus.equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            // 收集回调参数
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }

            // 验证支付宝通知的合法性
            String username = request.getParameter("subject");
            String record = params.get("total_amount");
            Long tradeId= Long.valueOf(params.get("out_trade_no"));
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过后的业务处理逻辑
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
                String username2=(String) redisTemplate.opsForValue().get("username");
                // 更新订单已支付的逻辑代码
                if(username.equals(username2)){
                    // 更新订单状态和处理后续业务逻辑
                    System.out.println("111111111");
                    userservice.updateBalanceByUsersId(Double.parseDouble(record), username);
                    rechargeRecordService.insertRechargeRecord(tradeId,Double.parseDouble(record), username);
                }
                else {
                    System.out.println("22222222");
                    String userstringid= (String) redisTemplate.opsForValue().get("userid");
                    int userid= Integer.parseInt(userstringid);
                    foodservice.finshapipalyorder(userid);

                }





            }
        }
        return "success";
    }

}
